import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:netstorage/model/response_result.dart';

class FutureStudy extends StatefulWidget {
  const FutureStudy({super.key});

  @override
  State<FutureStudy> createState() => _FutureStudyState();
}

class _FutureStudyState extends State<FutureStudy> {
  var postRes = '';
  @override
  Widget build(BuildContext context) {
    // return const Placeholder();
    return Scaffold(
      appBar: AppBar(title: Text('FutureStudy')),
      // 异步请求响应来的实体类是 ResponseResult
      body: FutureBuilder<ResponseResult>(
          future: fetchPost(),
          builder: (BuildContext context, AsyncSnapshot<ResponseResult> snapshot){
            switch(snapshot.connectionState){
              case ConnectionState.none:
                return const Text('state none');
              case ConnectionState.waiting:
                return const Center(child: CircularProgressIndicator());
              case ConnectionState.active:
                return const Text('state active');
              case ConnectionState.done:
                if(snapshot.hasError){
                  return Text('${snapshot.error}',style: const TextStyle(color: Colors.red));
                }else{
                  // snapshot.data = ResponseResult
                  Map<String,String>? map = snapshot.data?.data;
                  print('响应结果：$snapshot.data');
                  print('响应来的数据：$map');
                  String? msg = snapshot.data?.msg;
                  String? proxyUrl = '';
                  if(map != null) proxyUrl = map['proxyUrl'];
                  return Column(
                    children: [
                      Text('proxyUrl:$proxyUrl'),
                      Text('msg:$msg'),
                    ],
                  );
                }
            }
          },
      ),
    );
  }

  Future<ResponseResult<Map<String,String>>>? fetchPost() async {
    var uri = Uri.parse('https://www.xdfznh.club/wxpadbe/dev/proxyUrl');
    var params = {'rawUrl':'https://jzy.world'};
    var res = await http.post(
      uri,
      body: jsonEncode(params),
      headers: {
        'Content-Type': 'application/json; charset=UTF-8', // 关键：设置 Content-Type
      },
    );
    if(res.statusCode == 200){
      // 解析 json 数据为实体类
      var body = jsonDecode(res.body);

      // 上面接口响应来的是 Map<String,String> 而不是 ResponseResult
      // 所以要手动构建，保证异步请求方法返回数据的统一性
      ResponseResult<Map<String,String>> rr = ResponseResult();
      Map<String,String> mapData = {'proxyUrl':body['proxyUrl']};
      rr.code = 0; rr.success = true; rr.msg = '手动创建的响应结果'; rr.data = mapData;

      return rr;
    }else{
      print('异步请求出现异常');
      return ResponseResult.empty();
    }
  }
}
